package com.ecube.maintenance.components.fragment;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.ecube.maintenance.R;
import com.ecube.maintenance.biz.apis.impl.CarBrandAction;
import com.ecube.maintenance.biz.commons.IListItem;
import com.ecube.maintenance.components.widget.LoadingDialog;
import com.ecube.maintenance.managers.PrefManager;
import com.ecube.maintenance.pojos.CarPropertyListInfo;
import com.ecube.maintenance.pojos.UserInfo;
import com.ecube.maintenance.utils.Bog;

import java.util.List;

public class CarSelectorFragment extends CustomFragment {


    List<IListItem<CarPropertyListInfo.BaseCarPropertyList.BaseCarProperty>> brandData;
    List<IListItem<CarPropertyListInfo.BaseCarPropertyList.BaseCarProperty>> curData;
    int curBrandId = 0;
    int curSerialId = 0;
    int curStep = 0;
    String curBrand = "";
    String curSerial = "";
    String curModel = "";
    String curFactory = "";

    private OnFragmentInteractionListener mListener;
    private ListView mSelectorList;
    private CarSelectorAdapter mCarSelectorAdapter;
    private TextView mTitleView;

    private TextView brandTag;
    private TextView serialTag;
    private TextView modelTag;

    private TextView[] tagViews = new TextView[3];//保存品牌，车系，车型按钮的TextView

    public CarSelectorFragment() {
    }

    public static CarSelectorFragment newInstance() {
        CarSelectorFragment fragment = new CarSelectorFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
        new AsyncLoad().execute();
        setFragmentTitle("汽车品牌选择");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_type_select, container, false);

        mSelectorList = (ListView) rootView.findViewById(R.id.list_car_selector);
        mCarSelectorAdapter = new CarSelectorAdapter(getActivity());

        mTitleView = (TextView) rootView.findViewById(R.id.title);
        View.OnClickListener tagSelectListener = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                int step = 0;
                switch (v.getId()) {
                    case R.id.btn_brand_selector:
                        step = 0;
                        mTitleView.setText("品牌");
                        break;
                    case R.id.btn_serial_selector:
                        if (TextUtils.isEmpty(curBrand))
                            return;
                        step = 1;
                        mTitleView.setText("车系");
                        break;
                    case R.id.btn_model_selector:
                        if (TextUtils.isEmpty(curSerial))
                            return;
                        step = 2;
                        mTitleView.setText("车型");
                        break;
                    default:
                        break;
                }
                mCarSelectorAdapter.setStepAndUpdate(step);
            }
        };
        tagViews[0] = (TextView) rootView.findViewById(R.id.btn_brand_selector);
        tagViews[1] = (TextView) rootView.findViewById(R.id.btn_serial_selector);
        tagViews[2] = (TextView) rootView.findViewById(R.id.btn_model_selector);
        for (int i = 0; i < 3; i++) {
            tagViews[i].setOnClickListener(tagSelectListener);
        }

        return rootView;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        /*try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }*/
    }

    public void refreshWidgets() {

        for (int i = 1; i < 3; i++) {//0号不用换
            switchState(tagViews[i], curStep >= i);
        }


    }

    private void switchState(TextView tv, boolean active) {
        if (active) {
            tv.setBackgroundResource(R.drawable.selector_ict_red_bg);
            tv.setTextColor(getResources().getColor(R.color.white));
        } else {
            tv.setBackgroundResource(R.drawable.selector_ict_gray_bg);
            tv.setTextColor(getResources().getColor(R.color.ict_text_dark));
        }

    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        menu.clear();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        menu.findItem(R.id.action_map).setVisible(false);
    }

    @Override
    public void onResume() {
        super.onResume();
        configureActionBar();
    }

    private void configureActionBar() {
        ActionBar actionBar = getActivity().getActionBar();
        assert actionBar != null;
        View v = actionBar.getCustomView();
        if (v != null) {
            v.setVisibility(View.GONE);
        }
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle("车型选择");
    }

    public interface OnFragmentInteractionListener {
        public void onFragmentInteraction(Uri uri);
    }

    private class CarSelectorAdapter extends BaseAdapter {


        private LayoutInflater inflater;

        public CarSelectorAdapter(Context context) {
            inflater = LayoutInflater.from(context);

        }

        @Override
        public int getCount() {
            return curData == null ? 0 : curData.size();
        }

        @Override
        public Object getItem(int position) {
            return brandData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (curData.get(position).isSection()) {
                return getHeaderView(convertView, parent, curData.get(position).getSectionName());
            } else {
                return getCarView(convertView, parent, curData.get(position).getInfo());
            }
        }

        public View getCarView(View convertView, ViewGroup parent,
                               final IListItem<CarPropertyListInfo.BaseCarPropertyList.BaseCarProperty>
                                       carInfo) {
            ViewHolder holder;
            if (convertView == null ||
                    !(convertView.getTag() instanceof ViewHolder)) {
                holder = new ViewHolder();
                convertView = inflater.inflate(R.layout.item_list_city, parent, false);
                holder.text = (TextView) convertView;
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.text.setText(carInfo.getInfo().getName());
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PrefManager pm = PrefManager.getInstance();
                    switch (curStep) {
                        case 0://Brand selected
                            curBrandId = carInfo.getInfo().getId();
                            curBrand = carInfo.getInfo().getName();
                            mTitleView.setText("车系");
                            break;
                        case 1://Serial selected
                            curSerialId = carInfo.getInfo().getId();
                            curSerial = carInfo.getInfo().getName();
                            for (IListItem<CarPropertyListInfo.BaseCarPropertyList.BaseCarProperty> car : curData) {
                                if (car.isSection()) {
                                    curFactory = car.getSectionName();
                                } else {
                                    if (curSerial.equals(car.getInfo().getName())) {
                                        break;
                                    }
                                }
                            }
                            mTitleView.setText("车型");
                            break;
                        case 2://Model selected
//                            Bog.toast("选择完成" + curBrandId + "-" + curSerialId);
                            curModel = carInfo.getInfo().getName();
                            String section = "";
                            for (IListItem<CarPropertyListInfo.BaseCarPropertyList.BaseCarProperty> car : curData) {
                                if (car.isSection()) {
                                    section = car.getSectionName();
                                } else {
                                    if (curModel.equals(car.getInfo().getName())) {
                                        break;
                                    }
                                }
                            }
                            curModel = section + curModel;
                            UserInfo ui = UserInfo.getInstance();
                            ui.setCarBrand(curBrand);
                            ui.setCarSerial(curSerial);
                            ui.setCarModel(curModel);
                            ui.setCarFactory(curFactory);
                            getFragmentManager().popBackStack();
                            break;
                        default:
                            Bog.toast("未知数据");
                    }
                    curStep++;
                    updateData();
                }
            });
            return convertView;
        }

        public View getHeaderView(View convertView, ViewGroup parent, String section) {
            HeaderViewHolder holder;
            if (convertView == null ||
                    !(convertView.getTag() instanceof HeaderViewHolder)) {
                holder = new HeaderViewHolder();
                convertView = inflater.inflate(R.layout.item_list_city_header, parent, false);
                holder.text = (TextView) convertView;
                convertView.setTag(holder);
            } else {
                holder = (HeaderViewHolder) convertView.getTag();
            }
            holder.text.setText(section);
            return convertView;
        }

        private void updateData() {
            switch (curStep) {
                case 0:
                    curData = brandData;
                    break;
                case 1:
                    curData = CarBrandAction.getCarSerialsByBrandId(curBrandId);
                    break;
                case 2:
                    curData = CarBrandAction.getCarModelsByBrandIdAndSerialId(curBrandId, curSerialId);
                    break;

            }
            notifyDataSetChanged();
            refreshWidgets();
            mSelectorList.smoothScrollToPosition(0);
        }

        public void setStepAndUpdate(int step) {
            curStep = step;
            updateData();
        }

        class HeaderViewHolder {
            TextView text;
        }

        class ViewHolder {
            TextView text;
        }

    }

    public class AsyncLoad extends AsyncTask {
        LoadingDialog dialog = new LoadingDialog(getActivity());

        @Override
        protected void onPreExecute() {
            dialog.setTipText(getString(R.string.message_loading_car_selector));
            dialog.getDialog().setCancelable(false);
            dialog.show();
            super.onPreExecute();
        }

        @Override
        protected Object doInBackground(Object[] params) {
            while (!CarBrandAction.isInitCarInfos) ;
            return CarBrandAction.getCarBrands(getActivity());
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            brandData = (List<IListItem<CarPropertyListInfo.BaseCarPropertyList.BaseCarProperty>>) o;
            curData = brandData;
            curStep = 0;
            refreshWidgets();
            mSelectorList.setAdapter(mCarSelectorAdapter);
            dialog.getDialog().dismissDialogger();
        }
    }

}
